import {forwardRef, useEffect, useImperativeHandle, useRef, useState} from "react";
import {Html5Qrcode} from "html5-qrcode";
import "./index.scss";
import classNames from "classnames";

interface ScannerHandle {
  start: () => Promise<void>;
  stop: () => Promise<void>;
  isScanning: () => boolean;
}

interface ScannerProps {
  onScanSuccess: (result: string) => void;
  onClose?: () => void;
  width?: number;
}

const Scanner = forwardRef<ScannerHandle, ScannerProps>(({onScanSuccess, onClose}, ref) => {
  const qrRef = useRef<HTMLDivElement>(null);
  const qrInstance = useRef<Html5Qrcode | null>(null);
  const [lastScan, setLastScan] = useState<number>(0);
  const [scanning, setScanning] = useState<boolean>(false);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    start: () => initScanner(),
    stop: () => qrInstance.current?.stop() ?? Promise.resolve(),
    isScanning: () => scanning
  }));
  const handleClose = async () => {
    await handleScannerClose();
    onClose && onClose();
  };
  const handleScannerClose = async () => {
    // 判断是否在扫码中
    if (qrInstance.current?.isScanning) {
      await qrInstance.current
        ?.stop()
        .then(() => setScanning(false))
        .catch(() => {});
    }
  };

  // 初始化
  const initScanner = async () => {
    if (!qrRef.current) return;

    const html5QrCode = new Html5Qrcode(qrRef.current.id);
    qrInstance.current = html5QrCode;

    try {
      const {width} = window.screen;
      const currentWidth = parseInt(String(width * 0.5));
      await html5QrCode.start(
        {facingMode: "environment"},
        {
          fps: 1,
          qrbox: {
            width: currentWidth,
            height: currentWidth
          }
        },
        async decodedText => {
          const now = Date.now();
          if (now - lastScan < 3000) return;
          setLastScan(now);
          onScanSuccess(decodedText);
          await handleScannerClose();
        },
        () => {
          // handleClose();
          // handleClose();
        }
      );
    } catch (err) {
      // throw new Error("扫码失败", err);
      handleClose();
    }
  };

  useEffect(() => {
    initScanner();
    return () => {
      handleScannerClose();
    };
  }, []);

  return (
    <>
      <div className={classNames(["ToyHomeComponentsScanner", "scanner"])}>
        <div className="scanner-close" onClick={handleClose}>
          关闭
        </div>
        <div id="qr-reader" ref={qrRef}></div>
        <div className={"scanner-line"}></div>
      </div>
    </>
  );
});
export default Scanner;
